﻿using Microsoft.EntityFrameworkCore;
using System.Linq;
using System;
using JunYu.CodeGeneration.Models;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace JunYu.CodeGeneration
{
    public class CGDbContext:DbContext
    {
        public static DbContextOptions<CGDbContext> option;
        private readonly string _databaseName;
        //((Microsoft.EntityFrameworkCore.Infrastructure.RelationalOptionsExtension)(options.Extensions.ToArray()[1])).ConnectionString
        public CGDbContext(DbContextOptions<CGDbContext> options,string newCon) : base(options)
        {
            option = options;
            _databaseName = newCon;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            /*if(((RelationalOptionsExtension)option.Extensions.ToArray()[1]).ConnectionString == null)
                optionsBuilder.UseSqlServer(@"Data Source=192.168.3.6;Initial Catalog=CodeGenerationDb;User ID=sa;Password=123456");*/
            if (_databaseName!=null)
                optionsBuilder.UseSqlServer(_databaseName);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var Assembly = this.GetType().Assembly;
            var Types = Assembly.GetTypes()
                .Where(m => m.FullName != null 
                && typeof(EntityBase).IsAssignableFrom(m)
                && !m.IsAbstract
                && m.Name != "EntityBase").ToArray();
            foreach (var type in Types)
            {
                modelBuilder.Entity(type);
            }
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly);
            base.OnModelCreating(modelBuilder);
        }
    }
}
